<?php
/**
 * @author Raven <karascanvas@qq.com>
 */
namespace library\tencent\wechat\wechat_index;

use library\common\drawing\ImageSynthetise;
use think\Db;

abstract class OAuthManagement
{
    private function __construct() { }

    // <editor-fold defaultstate="collapsed" desc="判断数据库是否有openid">
    public static function if_exist_openid(array  $info){
        $record = Db::name('account_wechat')->where(['openid' => $info['openid']])->find();
        if(!$record){
            return false;
        };
        return true;
    }

    // </editor-fold>

    /**
     * 微信OAuth登录操作
     * @author Raven
     * @param array $info OAuth信息(access_token, expires_in, refresh_token, openid, scope, unionid)
     * @param string $ip 登录IP
     * @param bool $auto 是否自动创建账号
     * @return array|null 已绑定用户或自动创建账号时返回用户账号信息，未绑定或不自动创建时返回null
     */
    public static function login(array $info, $ip = 'unknown', $auto = true)
    {
        $data = [
            'scope'   => $info['scope'],
            'expires_in' => time() + $info['expires_in'],
            'access_token'  => $info['access_token'],
            'refresh_token' => $info['refresh_token'],
        ];

        if($info['subscribe']){
            $data['subscribe']=$info['subscribe'];
        }


        if($info['user_info']){
            $data['nickname']=$info['user_info']['nickname'];
            $data['sex']=$info['user_info']['sex'];
            $data['province']=$info['user_info']['province'];
            $data['city']=$info['user_info']['city'];
            $data['country']=$info['user_info']['country'];
            $data['headimgurl']=$info['user_info']['headimgurl'];
        }
        if (isset($info['unionid'])) {
            $data['unionid'] = $info['unionid'];
        }

        $exists = false;
        $accountId = 0;
        $record = Db::name('account_wechat')->where(['openid' => $info['openid']])->find();
        if (is_array($record)) {
            $exists = true;
            $accountId = $record['account_id'];
        }
        $account = null;
        if ($accountId > 0) {
            $account =  Db::name('account')->where(['id' => $accountId])->find();
            // throw exception when user not found ?
        }

        $data['account_id'] = $accountId;
        if ($exists) {
            Db::name('account_wechat')->where(['openid' => $info['openid']])->update($data);
        } else {
            $data['openid'] = $info['openid'];
            Db::startTrans();
            $url_res=self::save_headimg($info['user_info']['headimgurl']);
            $acc_data=array(
                'reg_time'=>time(),
                'reg_ip'=>$ip,
                'nick'=>$info['user_info']['nickname'],
                'password'=>md5('123456'),
                'name'=>$info['user_info']['nickname'],
                'sex'=>$info['user_info']['sex'],
//                'headimg'=>$info['user_info']['headimgurl']
                'headimg'=>$url_res
            );
            if($info['parent_id']){
                $acc_data['parent_id']=$info['parent_id'];
                Db::name('account')->where(['id'=>$info['parent_id']])->setField('flag_distributor',1);
//                $acc_data['flag_distributor']=1;
            }

            $res1=Db::name('account')->insertGetId($acc_data);

            $data['account_id'] = $res1;
            if(!$res1){
                Db::rollback();
                return $account;
            };
            $role_data=array(
                'account_id'=>$res1,
                'role_id'=>1,
                'add_time'=>time(),
                'update_time'=>time()
            );
            $res2=Db::name('account_role')->insert($role_data);
            if(!$res2){
                Db::rollback();
                return $account;
            };

            $res3=Db::name('account_wechat')->insert($data);
            if(!$res3){
                Db::rollback();
                return $account;
            };
            Db::commit();
            $account=Db::name('account')->where(['id'=>$res1])->find();
//            var_dump($res1);
//            var_dump($account);die();
        }

//        Db::name('user_wechat_oauth_log')->insert([
//            'time'    => time(),
//            'user_id' => $accountId,
//            'openid'  => $info['openid'],
//            'ip'      => $ip,
//        ]);

        return $account;
    }

    public static function save_headimg($url){
        $path=ImageSynthetise::create_path("./public/wechat/static/uploader/wx_uploader/",'png');
        $ch = curl_init();
        $httpheader = array(
            'Host' => 'mmbiz.qpic.cn',
            'Connection' => 'keep-alive',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'no-cache',
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
            'Accept-Encoding' => 'gzip, deflate, sdch',
            'Accept-Language' => 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
        );
        $options = array(
            CURLOPT_HTTPHEADER => $httpheader,
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_RETURNTRANSFER => true
        );
        curl_setopt_array( $ch , $options );
        $result = curl_exec( $ch );
        curl_close($ch);
        file_put_contents($path, $result);
        $CodePath=str_replace('./','/',$path);
        return $CodePath;
    }
}